const ACCOUNT = "18040585033";
const PASSWORD = "q461309827";
const QQ = "3024412629";
const PACKAGE_ID_QQ = "com.tencent.mobileqq";               // QQ
const PACKAGE_ID_DD = "com.alibaba.android.rimet";          // 钉钉
const PACKAGE_ID_TASKER = "net.dinglisch.android.taskerm";  // Tasker

// PackageId白名单
const PACKAGE_ID_WHITE_LIST = [PACKAGE_ID_QQ, PACKAGE_ID_DD, PACKAGE_ID_TASKER];

const WEEK_DAY = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// 检查无障碍权限
auto.waitFor();

// 监听本机通知
events.observeNotification()
events.on("notification", function (n) { notificationHandler(n); });

function notificationHandler(n) {
  const packageId = n.getPackageName();   // 获取通知包名
  const abstract = n.tickerText;          // 获取通知摘要
  const text = n.getText();               // 获取通知文本

  // 过滤 PackageId 白名单之外的应用所发出的通知
  if (!filterNotification(packageId, abstract, text)) {
    return;
  }

  switch (text) {
    case "打卡":
      needWaiting = false;
      threads.shutDownAll();
      threads.start(function () { doClock(); });
      break;
    case "查询":
      threads.shutDownAll();
      threads.start(function () { doCheckClock(); });
      break;
    case "测试":
      brightScreen();
      unlockScreen();
      break;
    case "锁屏":
      lockScreen();
      break;
    case "关闭":
      shutdownDingtalk();
      break;
    default: break;
  }
}

function shutdownDingtalk() {
  app.openAppSetting(PACKAGE_ID_DD);
  text("钉钉").waitFor();
  const closeButton = textContains("强行停止").findOne();
  if (closeButton.enabled()) {
    click("强行停止");
    textContains("确定").findOne();
    click("确定");
    console.log("钉钉已被关闭");
    home();
  } else {
    console.log("钉钉未能被正常关闭或不在后台运行");
    home();
  }
  sleep(1000);
}

/**
 * 唤醒屏幕
 */
function brightScreen() {
  console.log("唤醒设备");

  //device.setBrightnessMode(0); // 手动亮度模式
  //device.setBrightness(SCREEN_BRIGHTNESS);
  device.wakeUpIfNeeded(); // 唤醒设备
  sleep(1000);

  if (!device.isScreenOn()) {
    console.warn("设备未唤醒, 重试");
    device.wakeUpIfNeeded();
    brightScreen();
  }
  else {
    console.info("设备已唤醒");
  }
  sleep(1000);
}

/**
 * 解锁屏幕
*/
function unlockScreen() {
  console.log("解锁屏幕");

  if (isDeviceLocked()) {
    swipe(500, 2000, 500, 1000, 220);

    sleep(1000);
    home();
    sleep(1000);
  }

  if (isDeviceLocked()) {
    console.error("上滑解锁失败");
    return;
  }
  console.info("屏幕已解锁");
}

/**
 * 锁屏
 */
function lockScreen() {
  console.log("关闭屏幕");

  //device.setBrightnessMode(1); // 自动亮度模式

  // 双击任务栏锁屏
  sleep(1000);
  click(920, 52);
  sleep(100);
  click(920, 52);
}

/**
 * 通知过滤器,只处理白名单内的应用的通知
 * @param {string} packageId 通知包名
 * @param {string} abstract 通知摘要
 * @param {string} text 通知文本
 * @returns
 */
function filterNotification(packageId, abstract, text) {
  const check = PACKAGE_ID_WHITE_LIST.some(function (item) { return packageId == item });
  if (check) {
    console.verbose("┌─────────────────────────────────────┐");
    console.verbose("│ 通知包名: " + packageId);
    console.verbose("│ 通知摘要: " + abstract);
    console.verbose("│ 通知文本: " + text);
    console.verbose("└─────────────────────────────────────┘");
  }
  return check;
}

function dateDigitToString(num) {
  //return num < 10 ? '0' + num : num;
  return num.toString().padStart(2, '0');
}

function getCurrentTime() {
  const currentDate = new Date();
  const hours = dateDigitToString(currentDate.getHours());
  const minute = dateDigitToString(currentDate.getMinutes());
  const second = dateDigitToString(currentDate.getSeconds());
  const formattedTimeString = hours + ':' + minute + ':' + second;
  return formattedTimeString;
}

function getCurrentDate() {
  const currentDate = new Date();
  const year = dateDigitToString(currentDate.getFullYear());
  const month = dateDigitToString(currentDate.getMonth() + 1);
  const date = dateDigitToString(currentDate.getDate());
  const week = currentDate.getDay();
  const formattedDateString = year + '-' + month + '-' + date + '-' + WEEK_DAY[week];
  return formattedDateString;
}

// 屏幕是否为锁定状态
function isDeviceLocked() {
  importClass(android.app.KeyguardManager);
  importClass(android.content.Context);
  const km = context.getSystemService(Context.KEYGUARD_SERVICE);
  return km.isKeyguardLocked();
}

// 设置媒体和通知音量
function setVolume(volume) {
  device.setMusicVolume(volume);
  device.setNotificationVolume(volume);
  console.verbose("媒体音量:" + device.getMusicVolume());
  console.verbose("通知音量:" + device.getNotificationVolume());
}
